import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import classNames from 'classnames'
import {
  changeTodoStatus,
  checkAllTodo,
  delTodo,
} from '../../store/actions/todo'

export default function TodoMain() {
  const inputRef = useRef(null)
  const dispatch = useDispatch()
  const list = useSelector((state) => state.todo)
  const handleTodoDel = (id) => dispatch(delTodo(id))
  const handleChangeStatus = (id) => dispatch(changeTodoStatus(id))
  // !先确定全选的状态，根据所有的单选状态来判断
  const isChecked = list.every((item) => item.done)
  const handleChangeAll = () => dispatch(checkAllTodo(!isChecked))
  // 显示编辑框，准备一个变量用于控制编辑框的显示与否
  const [currentId, setCurrentId] = useState('')
  // 把当前双击的那一项的 item.id 给 currentId
  const handleDBLClick = (id) => {
    // 显示编辑框
    setCurrentId(id)
  }
  // 只有等 id 变化完毕之后才应该获取焦点比较合适，获取焦点
  useEffect(() => {
    inputRef.current.focus()
  }, [currentId])
  return (
    <section className='main'>
      <input
        id='toggle-all'
        className='toggle-all'
        type='checkbox'
        checked={isChecked}
        onChange={handleChangeAll}
      />
      <label htmlFor='toggle-all'>Mark all as complete</label>
      <ul className='todo-list'>
        {list.map((item) => (
          <li
            key={item.id}
            className={classNames({
              completed: item.done,
              editing: item.id === currentId,
            })}
          >
            <div className='view'>
              <input
                className='toggle'
                type='checkbox'
                checked={item.done}
                onChange={() => handleChangeStatus(item.id)}
              />
              <label onDoubleClick={() => handleDBLClick(item.id)}>
                {item.name}
              </label>
              <button
                className='destroy'
                onClick={() => handleTodoDel(item.id)}
              ></button>
            </div>
            {/* 编辑功能 */}
            <input
              className='edit'
              value={`Create a TodoMVC template${item.id}`}
              onChange={() => {}}
              ref={inputRef}
            />
          </li>
        ))}
      </ul>
    </section>
  )
}
